<%--
  Created by IntelliJ IDEA.
  User: DCQ
  Date: 2025/3/6
  Time: 11:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"
         isELIgnored="false" %>
<%@ taglib prefix="rapid" uri="http://www.rapid-framework.org.cn/rapid" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<rapid:override name="title">部门管理</rapid:override>

<rapid:override name="head_extend">
    <link href="/static/admin_v1/css/addTable.css" rel="stylesheet"/>
    <style>

        /* 基础样式 */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 20px;
            background: #f0f2f5;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            padding: 24px;
        }

        /* 搜索区域 */
        .search-bar {
            display: flex;
            gap: 16px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .search-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .search-item input,
        .search-item select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-width: 180px;
        }

        /* 操作按钮 */
        .action-bar {
            margin: 16px 0;
            display: flex;
            gap: 8px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #1890ff;
            color: white;
        }

        .btn-warning {
            background: #faad14;
            color: white;
        }

        /* 数据表格 */
        .dept-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 16px;
        }

        .dept-table th,
        .dept-table td {
            padding: 12px;
            border-bottom: 1px solid #eee;
            text-align: left;
        }

        .dept-table th {
            background: #fafafa;
            font-weight: 500;
        }

        .dept-checkbox {
            margin-right: 8px;
        }

        .op-cell a {
            color: #1890ff;
            text-decoration: none;
            margin-right: 12px;
        }

        .op-cell a:hover {
            text-decoration: underline;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgb(0, 0, 0);
            background-color: rgba(0, 0, 0, 0.4);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }

        .close {
            color: #aaaaaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: red;
            text-decoration: none;
            cursor: pointer;
        }

    </style>
    <%--    树形--%>
    <link href="/static/admin_v1/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/admin_v1/css/plugins/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.bootcss.com/jquery-treegrid/0.2.0/css/jquery.treegrid.min.css">
    <script src="https://cdn.bootcss.com/bootstrap-table/1.12.1/bootstrap-table.min.js"></script>
    <script src="/static/admin_v1/js/bootstrap-table-treegrid.js"></script>
    <script src="/static/admin_v1/js/jquery.treegrid.min.js"></script>

</rapid:override>

<rapid:override name="content">

    <div class="row" style="height: 100%">
    <div id="modal" class="modal" style="display: none;">
        <div class="modal-content">
            <span class="close">×</span>
            <h2 id="h0">新增部门</h2>
            <div class="ibox-content">
                <form class="form-horizontal" id="dataForm" action="/admin/department/add" method="post">
                    <div class="form-group">
                        <label class="col-sm-3 control-label">部门名称</label>
                        <div class="col-sm-8">
                            <input type="text" name="departmentName" placeholder="请输入新增部门名称"
                                   class="form-control">

                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">父级部门</label>
                        <div class="col-sm-8">
                            <select id="pid" class="form-control m-b" name="pid">

                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">部门负责人</label>
                        <div class="col-sm-8">
                            <select id="chairman" class="form-control m-b" name="chairmanId">

                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-sm-offset-3 col-sm-8">
                            <button class="btn btn-sm btn-info" type="submit">新增</button>
                        </div>
                    </div>
                    <button type="button" class="close">取消</button>
                </form>
            </div>
        </div>
    </div>
    <div class="container">
        <!-- 搜索区域 -->
        <div class="search-bar">
            <div class="search-item">
                <span>部门名称：</span>
                <input type="text" id="addDeptName">
            </div>
            <div class="search-item">
                <span>部门状态：</span>
                <select id="addDeptStatus">
                    <option value="">全部</option>
                    <option value="1">正常</option>
                    <option value="0">停用</option>
                </select>
            </div>
            <button class="btn btn-primary" onclick="doSearch()">搜索</button>
        </div>

        <!-- 操作按钮 -->
        <div class="action-bar">
            <button class="btn btn-primary" onclick="showAddModal()" id="addButton">添加</button>
            <button class="btn btn-primary" onclick="editDept()">修改</button>
            <button class="btn btn-warning" onclick="toggleCollapse()">展开/折叠</button>
        </div>

        <table id="table"></table>
        <button onclick="test()">选择</button>


    </div>

</rapid:override>

<rapid:override name="js_extend">

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const newButton = document.getElementById('addButton');
            const modal = document.getElementById('modal');
            const closeButtons = document.querySelectorAll('.close');
            const dataForm = document.getElementById('dataForm');

            // 打开模态窗口
            newButton.onclick = function () {
                modal.style.display = 'block';
            }

            // 关闭模态窗口
            closeButtons.forEach(button => {
                button.onclick = function () {
                    modal.style.display = 'none';
                }
            });
            // 点击窗口外的区域也关闭窗口
            window.onclick = function (event) {
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            }
        });
    </script>



    <script type="text/javascript">

        var $table = $('#table');
        <%--var data = JSON.parse(--%>
        <%--    '['+<c:forEach items="${departmentList}" var="department" varStatus="status">--%>
        <%--    '{"id":${department.id},"pid":${department.pid},"status":${department.status},"departmentName":"${department.departmentName}","chairman":"${department.chairman}","creator":"${department.creator}","createTime":""}'+--%>
        <%--    <c:if test="${!status.last}">--%>
        <%--    ","+--%>
        <%--    </c:if>--%>
        <%--    </c:forEach>']'--%>
        <%--    );--%>
        (async () => {
            try {
                const response = await fetch('/admin/department/find');
                if (!response.ok) throw new Error(`HTTP错误: ${response.status}`);
                const data = await response.json();
                tree(data); // 数据就绪后执行
            } catch (error) {
                console.error('加载数据失败:', error);
            }
        })();

        function tree (data) {
            //控制台输出一下数据
            $table.bootstrapTable({
                data: data,
                idField: 'id',
                dataType: 'jsonp',
                columns: [
                    {
                        field: 'check', checkbox: true, formatter: function (value, row, index) {
                            if (row.check == true) {
                                // console.log(row.serverName);
                                //设置选中
                                return {checked: true};
                            }
                        }
                    },
                    {field: 'departmentName', title: '名称'},
                    // {field: 'id', title: '编号', sortable: true, align: 'center'},
                    // {field: 'pid', title: '所属上级'},
                    {field: 'status', title: '状态', sortable: true, align: 'center', formatter: 'statusFormatter'},
                    {field: 'chairman', title: '部门负责人'},
                    {field: 'creator',title: '创建人'},
                    {
                        field: 'operate',
                        title: '操作',
                        align: 'center',
                        events: operateEvents,
                        formatter: 'operateFormatter'
                    },
                ],

                // bootstrap-table-treegrid.js 插件配置 -- start

                //在哪一列展开树形
                treeShowField: 'departmentName',
                //指定父id列
                parentIdField: 'pid',

                onResetView: function (data) {
                    //console.log('load');
                    $table.treegrid({
                        initialState: 'collapsed',// 所有节点都折叠
                        // initialState: 'expanded',// 所有节点都展开，默认展开
                        treeColumn: 1,
                        // expanderExpandedClass: 'glyphicon glyphicon-minus',  //图标样式
                        // expanderCollapsedClass: 'glyphicon glyphicon-plus',
                        onChange: function () {
                            $table.bootstrapTable('resetWidth');
                        }
                    });

                    //只展开树形的第一级节点
                    $table.treegrid('getRootNodes').treegrid('expand');

                },
                onCheck: function (row) {
                    var datas = $table.bootstrapTable('getData');
                    // 勾选子类
                    selectChilds(datas, row, "id", "pid", true);

                    // 勾选父类
                    selectParentChecked(datas, row, "id", "pid")

                    // 刷新数据
                    $table.bootstrapTable('load', datas);
                },

                onUncheck: function (row) {
                    var datas = $table.bootstrapTable('getData');
                    selectChilds(datas, row, "id", "pid", false);
                    $table.bootstrapTable('load', datas);
                },
                // bootstrap-table-treetreegrid.js 插件配置 -- end
            });
        };

        // 格式化按钮
        function operateFormatter(value, row, index) {
            return [
                '<button type="button" class="RoleOfdelete btn-small   btn-primary" style="margin-right:15px;"><i class="fa fa-pencil-square-o" ></i>&nbsp;删除</button>',
            ].join('');

        }

        // 格式化类型
        function typeFormatter(value, row, index) {
            if (value === 'menu') {
                return '菜单';
            }
            if (value === 'button') {
                return '按钮';
            }
            if (value === 'api') {
                return '接口';
            }
            return '-';
        }

        // 格式化状态
        function statusFormatter(value, row, index) {
            if (value === 1) {
                return '<span class="label label-success">正常</span>';
            } else {
                return '<span class="label label-default">锁定</span>';
            }
        }

        //初始化操作按钮的方法
        window.operateEvents = {
            'click .RoleOfadd': function (e, value, row, index) {
                add(row.id);
            },
            'click .RoleOfdelete': function (e, value, row, index) {
                del(row.id);
            },
            'click .RoleOfedit': function (e, value, row, index) {
                update(row.id);
            }
        };
    </script>
    <script>
        /**
         * 选中父项时，同时选中子项
         * @param datas 所有的数据
         * @param row 当前数据
         * @param id id 字段名
         * @param pid 父id字段名
         */
        function selectChilds(datas, row, id, pid, checked) {
            for (var i in datas) {
                if (datas[i][pid] == row[id]) {
                    datas[i].check = checked;
                    selectChilds(datas, datas[i], id, pid, checked);
                }
                ;
            }
        }

        function selectParentChecked(datas, row, id, pid) {
            for (var i in datas) {
                if (datas[i][id] == row[pid]) {
                    datas[i].check = true;
                    selectParentChecked(datas, datas[i], id, pid);
                }
                ;
            }
        }

        function test() {
            var selRows = $table.bootstrapTable("getSelections");
            if (selRows.length == 0) {
                alert("请至少选择一行");
                return;
            }

            var postData = "";
            $.each(selRows, function (i) {
                postData += this.id;
                if (i < selRows.length - 1) {
                    postData += "， ";
                }
            });
            alert("你选中行的 id 为：" + postData);

        }

        function add(id) {
            alert("add 方法 , id = " + id);
        }

        function del(id) {
            $.ajax({
                url: "/admin/department/delete/"+id,
                dataType: "json",
                method: "get",
                success:res=>{
                    window.location.href="/jsp/admin/department.jsp"
                }
            })
        }

        function update(id) {
            alert("update 方法 , id = " + id);
        }


    </script>
    <script>
        $.ajax({
            url:'/admin/department/find/id',
            method:"get",
            dataType: "json",
            success:res=>{
                for(var i in res){
                    map=res[i]
                    $('#pid').append(
                        '<option value="'+map.id+'">'+map.departmentName+'</option>'
                    )
                }
            }
        });
        $.ajax({
            url:'/admin/user/find/id',
            method:"get",
            dataType: "json",
            success:res=>{
                for(var i in res){
                    map=res[i]
                    $('#chairman').append(
                        '<option value="'+map.userId+'">'+map.userName+'</option>'
                    )
                }
            }
        })
    </script>


</rapid:override>

<%@include file="/jsp/common/admin/base.jsp" %>